<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, onMounted, nextTick } from 'vue'
import { reqAllUserAPI, reqAddOrUpdateUserAPI, reqGetRoleListAPI, reqUpdateRoleListAPI, reqDeleteUserAPI, reqBatchDeleteUserAPI } from '@/apis/acl/user'
import type { User, AllRole } from '@/apis/acl/user/type'

//分页器当前页码
let pageNo = ref<number>(1)
//分页器每页数量
let pageSize = ref<number>(5)
//控制对话框显示隐藏
let isShow = ref<boolean>(false)
//控制角色分配显示隐藏
let isShowRole = ref<boolean>(false)
//储存接口所有用户数据
let allUser = ref<User[]>([])
//储存用户个数
let total = ref<number>(0)
//收集对话框数据
let userParams = ref<User>({
    username: '',
    password: '',
    name: '',
})
//表单实例
let formRef = ref()
const getAllUser = async (pager = 1) => {
    pageNo.value = pager
    let result = await reqAllUserAPI(pageNo.value, pageSize.value, keyWord.value)
    if (result.code == 200) {
        allUser.value = result.data.records
        total.value = result.data.total
    }
}
onMounted(() => {
    getAllUser()
})
//分页器每页数量改变
const handler = (val: number) => {
    getAllUser()
}
//点击添加按钮点击添加用户
const addUser = () => {
    //重置表单数据
    userParams.value.id = ''
    userParams.value.username = ''
    userParams.value.password = ''
    userParams.value.name = ''
    //清除上一次表单提示信息
    nextTick(() => {
        formRef.value.resetFields()
    })
    isShow.value = true
}
//点击编辑按钮
const updateUser = (row: User) => {
    userParams.value.id = row.id
    userParams.value.username = row.username
    userParams.value.name = row.name
    isShow.value = true
    //清除上一次表单提示信息
    nextTick(() => {
        formRef.value.resetFields()
    })
}
//点击保存按钮
const save = async () => {
    //表单效验通过后才能发请求
    await formRef.value.validate()
    const result = await reqAddOrUpdateUserAPI(userParams.value)
    if (result.code == 200) {
        isShow.value = false
        ElMessage.success(userParams.value.id ? '修改成功' : '添加成功')
        getAllUser()
    } else {
        ElMessage.error(userParams.value.id ? '修改失败' : '添加失败')
    }
}
//表单效验
const validatorUsername = (rule: any, value: string, callback: any) => {
    if (!value || value.trim().length === 0) {
        callback(new Error('用户名不能为空'));
        return;
    }
    // 实时验证：当输入符合要求时立即清除错误
    if (value.length >= 3 && value.length <= 10) {
        callback(); // 显式调用空回调清除错误
        return;
    }
    // 长度验证
    callback(new Error('用户名长度需在3-10个字符'));
};
//对话框表单效验
const rules = {
    username: [
        { required: true, trigger: 'blur', validator: validatorUsername },
    ],
    name: [
        { required: true, min: 3, max: 10, message: '长度在 3到 10 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
    ]
}
//储存所有职位接口
let allrole = ref<AllRole>([])
//当前用户已有职业
let userRole = ref<AllRole>([])
//角色分配按钮
const setRole = async (row: User) => {
    userParams.value.id = row.id
    userParams.value.username = row.username
    const result = await reqGetRoleListAPI((row.id as number))
    if (result.code == 200) {
        allrole.value = result.data.allRolesList
        userRole.value = result.data.assignRoles
        isShowRole.value = true
    }
}
//全选框
let checkAll = ref<boolean>(false)
//设置不确定样式，仅负责全选框样式控制
let checkIndeterminate = ref<boolean>(true)
//全选框变化事件
const handleCheckAllChange = (val: boolean) => {
    userRole.value = val ? allrole.value : []
    checkIndeterminate.value = false
}
//复选框变化事件
const handleCheckedCitiesChange = (value: string[]) => {
    checkAll.value = value.length === allrole.value.length
    checkIndeterminate.value = value.length > 0 && value.length < allrole.value.length
}
//职位对话框确定按钮
const saveRole = async () => {
    const data = {
        roleIdList: userRole.value.map(item => {
            return (item.id as number)
        }),
        userId: (userParams.value.id as number)
    }
    const result = await reqUpdateRoleListAPI(data)
    if (result.code == 200) {
        ElMessage.success('分配成功')
        isShowRole.value = false
        getAllUser()
    } else {
        ElMessage.error('分配失败')
    }
}
//点击删除按钮
const deleteUser = async (row: User) => {
    const result = await reqDeleteUserAPI((row.id as number))
    if (result.code == 200) {
        ElMessage.success('删除成功')
        getAllUser()
    } else {
        ElMessage.error('删除失败')
    }
}
//表格复选框选中数据数组
let selectUser = ref<number[]>([])
//表格复选框选中事件
const handleSelectionChange = (val: any) => {
    selectUser.value = val.map((item: any) => item.id)
}
//批量删除按钮
const deleteAllUser = async () => {
    const result = await reqBatchDeleteUserAPI(selectUser.value)
    if (result.code == 200) {
        ElMessage.success('删除成功')
        getAllUser()
    } else {
        ElMessage.error('删除失败')
    }
}
//搜索input框数据
let keyWord = ref<any>('')
//点击搜索按钮
const findUser = async () => {
    getAllUser()
    // 清空搜索框数据
    keyWord.value = ''
}
//点击重置按钮
const clearUser = () => {
    keyWord.value = ''
    getAllUser()
}
</script>
<template>
    <el-card style="height: 80px;">
        <el-form class="form" inline>
            <el-form-item label="用户名:">
                <el-input v-model="keyWord" style="width: 240px;" placeholder="请输入用户名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyWord.trim().length === 0" @click="findUser">搜索</el-button>
                <el-button @click="clearUser">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card>
        <el-button type="primary" @click="addUser">添加</el-button>
        <el-button type="danger" @click="deleteAllUser">批量删除</el-button>
        <!-- 表格 -->
        <el-table border :data="allUser" @selection-change="handleSelectionChange">
            <el-table-column type="selection"></el-table-column>
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column label="id" width="80" prop="id"></el-table-column>
            <el-table-column label="用户名字" prop="username"></el-table-column>
            <el-table-column label="用户名称" prop="name"></el-table-column>
            <el-table-column label="用户角色" prop="roleName"></el-table-column>
            <el-table-column label="创建时间" prop="createTime"></el-table-column>
            <el-table-column label="更新时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="300">
                <template #="{ row }">
                    <el-button type="primary" size="small" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" @click="updateUser(row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="deleteUser(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination class="spu-pagination" :pager-count="5" background v-model:current-page="pageNo"
            v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 10]" layout="prev, pager, next, jumper, ->,sizes, total"
            :total="total" @current-change="getAllUser" @size-change="handler">
        </el-pagination>
        <!-- drawer抽屉对话框 -->
        <el-drawer v-model="isShow" direction="rtl">
            <template #header>
                <span>{{ userParams.id ? '修改用户' : '添加用户' }}</span>
            </template>
            <template #default>
                <el-form :model="userParams" :rules="rules" ref="formRef">
                    <el-form-item label="用户姓名" prop="username">
                        <el-input v-model="userParams.username" placeholder="请输入用户姓名"></el-input>
                    </el-form-item>
                    <el-form-item label="用户昵称" prop="name">
                        <el-input v-model="userParams.name" placeholder="请输入用户昵称"></el-input>
                    </el-form-item>
                    <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
                        <el-input v-model="userParams.password" placeholder="请输入用户密码"></el-input>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="isShow = false">取消</el-button>
            </template>
        </el-drawer>
        <!-- 分配角色抽屉对话框 -->
        <el-drawer v-model="isShowRole" direction="rtl">
            <template #header>
                <span>分配角色</span>
            </template>
            <template #default>
                <el-form>
                    <el-form-item label="用户姓名">
                        <el-input v-model="userParams.username" placeholder="请输入用户姓名" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="职位列表">
                        <el-checkbox v-model="checkAll" :indeterminate="checkIndeterminate"
                            @change="handleCheckAllChange">全选</el-checkbox>
                        <el-checkbox-group v-model="userRole" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="(role, index) in allrole" :key="index" :label="role">{{ role.roleName
                            }}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button type="primary" @click="saveRole">确定</el-button>
                <el-button>取消</el-button>
            </template>
        </el-drawer>
    </el-card>
</template>
<style scoped>
.el-card {
    margin: 20px 0;
}

.form {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-table {
    margin: 10px 0;
}
</style>